package com.wsd.socket.step4;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
  *    手写httpServer   第四步  抽象 request response对象
 * @author fengmoboy
 *
 */
public class Step4Server {
	
	/**
	 * socket服务
	 */
	public ServerSocket socketServer;
	
	/**
	 * 传入处理逻辑
	 */
	public IHandlerInterface httpHandler;
	
	
	public Step4Server(IHandlerInterface httpHandler) {
		this.httpHandler = httpHandler;
	}
	
	// Pending Queue
	public void listen(int port) throws IOException {
		socketServer = new ServerSocket(port);
		
		// Main Thread
		while(true) {
			this.accept();
		}
	}
	
	public void accept() throws IOException {
		// Blocking...
		Socket socket = socketServer.accept();
		new Thread(() -> {
			try {
				this.handler(socket);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}).start();
	}
	
	public void handler(Socket socket) throws IOException{
			
		Request request = new Request(socket);
		Response response = new Response(socket);
		System.out.println("A socket created");
		this.httpHandler.handler(request, response);
			
	}
	
	public static void main(String[] args) throws IOException {
		Step4Server step4Server = new Step4Server((req, resp) -> {
//			try {
//				Thread.sleep(10);
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
			System.out.println(req.getHeadMap());
			resp.send("<html><body><h1>Hello World!</h1></body></html>\n");
		});
		step4Server.listen(8000);
	}
}
